package com.example.netty02;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @Date 2022/10/22
 * @Author Jonathan
 */
public class MyNettyClient {

    private static final Logger log = LoggerFactory.getLogger(MyNettyClient.class);

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        bootstrap.group(eventExecutors);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel channel) throws Exception {
                channel.pipeline().addLast(new ObjectEncoder());
                channel.pipeline().addLast(new LoggingHandler());
            }
        });

        // 起了一个新的线程，用于连接
        Channel channel = bootstrap.connect(new InetSocketAddress(8080)).sync().channel();
        User user = new User("张三", 100);
        channel.writeAndFlush(user);
        log.info("消息:{}发送成功", user);
        ChannelFuture closeFuture = channel.close();// 关闭channel是异步的
        closeFuture.sync();
        eventExecutors.shutdownGracefully();
    }
}

